#!/bin/sh
set -e 
PKGNAME="kidux-emesene-plugin"
MAINTAINER="Tiago"
MAINTMAIL="tiago@kidux.net"
DIST="unstable"
MAINVERSION="0.1"
KEY="A8E8DE09"
BUILDDIR=$PWD
CHANGEFILE="$BUILDDIR/debian/changelog"

prebuild(){
    svn up
    DATE=`date +"%a, %d %b %Y %H:%M:%S %z"`
    SVNLOG=`svn log -r COMMITTED`
    REVISION=$MAINVERSION"svn"`echo "$SVNLOG" |sed -n '2s/^r\([0-9]\+\).*$/\1/p' `
    MESSAGE=`echo "$SVNLOG" |sed -n '/^$/,$p' | sed '/^$/d' | sed '/^-\+$/d'`
    OLDCHANGELOG=`cat $CHANGEFILE`
    FILENAME=$PKGNAME"_"$REVISION
}

update_changelog() {
    CHANGES="$PKGNAME ($REVISION) $DIST; urgency=low\n\n * $MESSAGE\n\n -- $MAINTAINER <$MAINTMAIL> $DATE\n\n"
    CHANGELOG="$CHANGES$OLDCHANGELOG"
    echo "$CHANGES"
    echo "$CHANGELOG" > $CHANGEFILE
}

deploy() {
    cd $BUILDDIR
    dpkg-buildpackage -sgpg -k"$KEY" -I/.svn
    scp ../"$FILENAME"* kidux.net:/opt/incoming
#    cp ../"$FILENAME"* /opt/incoming
    rm -f ../"$FILENAME"*
}


build_package() {
    update_changelog
    deploy
}

test_build() {
    for i in $OLDCHANGELOG;do
        if [ "$i" = "($REVISION)"  ]; then
            OLD_REVISION="$i"
        fi
    done
    if [ "($REVISION)" != "$OLD_REVISION" ];then
        build_package
        echo "Criando pacote para $PKGNAME"
    else
        echo "Pacote atualizado na versão $OLD_REVISION, não será refeito"
    fi
}
prebuild
test_build
